<template>
  <div class="order-card">
    <div class="top">
      <span>{{ trainNumber }} ｜ {{ trainData }}</span>
      <span class="status">{{ statusText }}</span>
    </div>
    <div class="middle">
      <div class="stations">
        <strong>{{ departureStationName }}</strong>
        <span>→</span>
        <strong>{{ arriveStationName }}</strong>
      </div>
      <div class="time">{{ formatTime(departureTime) }} - {{ formatTime(arrivalTime) }}</div>
    </div>
    <div class="seat-info">
      <span>车厢 {{ carriageNumber }} · 座位 {{ seatNumber }}（{{ seatType }}）</span>
    </div>
    <div class="passenger">
      <span>乘客：{{ passengerName }} ｜ {{ passengerIdCard }}</span>
    </div>
    <div class="bottom">
      <div>
        <button v-if="ticketStatus === 0" class="refund-button" @click="refundTicket">退票</button>
        <span class="time">支付时间：{{ formatDateTime(paymentTime) }}</span>
      </div>
      <div class="price">￥{{ price.toFixed(2) }}</div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed } from 'vue'
import type { TrainOrderDTO } from '@/types/trainOrder'
import api from '@/utils/api'

const props = defineProps<TrainOrderDTO>()
const statusText = computed(() => {
  switch (props.ticketStatus) {
    case 0:
      return '已支付'
    case 1:
      return '已退票'
    case 2:
      return '已使用'
    default:
      return '未知状态'
  }
})
const emit = defineEmits(['refundSuccess']) //刷新表单

function formatTime(t: string) {
  return t.slice(0, 5)
}
function formatDateTime(dt: string) {
  return dt?.replace('T', ' ').slice(0, 16) || '—'
}

async function refundTicket() {
  try {
    // 发送退票请求，传递 orderId
    await api.post('/api/orders/refund', { orderId: props.orderId })
    alert(`退票成功`)
    // 如果需要，可以触发刷新订单列表的事件或其他逻辑
    emit('refundSuccess', props.orderId)

    //创建退票消息
    const message = {
      userName: props.userName,
      messageType: 0, // 火车票
      actionType: '退票成功',
      content: `您已成功退订 ${props.trainData} ${props.departureStationName} 到 ${props.arriveStationName} 的 ${props.trainNumber} 车次车票，乘客姓名：${props.passengerName}。欢迎您再次使用风行旅途平台，祝您生活愉快！`,
    }
    const messageRes = await fetch('http://localhost:9000/api/message/set', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(message),
    })
    if (!messageRes.ok) {
      console.warn('退票成功，但消息发送失败')
    }
  } catch (error) {
    console.error('退票失败', error)
    alert('退票失败，请稍后重试')
  }
}
</script>

<style scoped>
.order-card {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
  display: flex;
  flex-direction: column;
  gap: 6px;
}
.top {
  display: flex;
  justify-content: space-between;
  font-weight: 600;
  font-size: 15px;
}
.middle .stations {
  font-size: 16px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
}
.middle .time {
  font-size: 13px;
  color: #888;
}
.seat-info,
.passenger {
  font-size: 14px;
  color: #444;
}
.bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #555;
}
.bottom .price {
  font-size: 18px;
  color: #e53935;
  font-weight: bold;
}
.status {
  color: #409eff;
}
.refund-button {
  background-color: #f56c6c;
  color: white;
  border: none;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  margin-bottom: 4px;
}
.refund-button:hover {
  background-color: #dd6161;
}
</style>
